<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2018/11/12
 * Time: 10:13
 */

namespace Order\Model;

use Common\Model\CommonModel;

class OrderModel extends CommonModel {
    protected $name     = 'order';
    protected $pk       = 'id';

    // 订单失效时间
    const ORDER_EXPIRE_TIME         = 600;

    // 订单状态
    const ORDER_STATUS_NOT_PAY      = 1;    // 未支付
    const ORDER_STATUS_HAS_PAY      = 2;    // 已支付
    const ORDER_STATUS_EXPIRE       = 3;    // 过期
    const ORDER_STATUS_PAY_FAIL     = 4;    // 支付失败
    const ORDER_STATUS_REFUND       = 5;    // 主动退票

    // 订单类型
    const ORDER_TYPE_ACT_TICKET     = 1;    // 活动购票
    const ORDER_TYPE_QUESTION       = 2;    // 查看问题答案
    const ORDER_TYPE_LESSON         = 3;    // 课程

    // 退款状态
    const ORDER_REFUND_STATUS_NORMAL    = 0;    // 正常
    const ORDER_REFUND_STATUS_ING       = 1;    // 申请中
    const ORDER_REFUND_STATUS_HAS       = 2;    // 已退款
    const ORDER_REFUND_STATUS_FAILED    = 3;    // 退款失败
    const ORDER_REFUND_STATUS_SELF      = 4;    // 取消订单


    // 支付方式
    const ORDER_PAY_TYPE_WX_NATIVE  = 1;    // 微信支付--native 扫码支付
    const ORDER_PAY_TYPE_WX_H5      = 2;    // 微信支付--H5 调起微信客户端支付
    const ORDER_PAY_TYPE_WX_JSAPI   = 3;    // 微信支付--JASPI 公众号内调起微信支付
    const ORDER_PAY_TYPE_WX_MINI    = 4;    // 微信支付--小程序内支付




    // 检查购票限制
    // return  可购票数量
    public function checkTicketLimit($user_id, $type, $goods_id, $limit)
    {
        $hasBuy = $this->where(['user_id' => $user_id, 'type' => $type, 'goods_id' => $goods_id, 'status' => self::ORDER_STATUS_HAS_PAY])->sum('goods_num');
        if (intval($hasBuy) >= intval($limit)) {
            return 0;
        } else {
            return intval($limit) - intval($hasBuy);
        }
    }

    // 检查是否有未完成订单
    public function CheckOldOrder($user_id, $type, $goods_id, $total_money, $trade_order_id = 0, $need_expire = false)
    {
        // 查询是否是已有订单
        $notPay = $this->where(['type' => $type, 'user_id' => $user_id, 'goods_id' => $goods_id, 'status' => self::ORDER_STATUS_NOT_PAY])->order('created_at desc')->find();
        if ($notPay) {
            if (($notPay['created_at'] < time() - self::ORDER_EXPIRE_TIME) && !$need_expire) {
                // 过期，新建订单
                $return['status'] = 1;
                return $return;
            } else {
                // 沿用之前的订单
                $new_trade_order_id = $trade_order_id ?: $this->_rand_trade_order_id();
                $this->where(['id' => $notPay['id']])->save(['trade_order_id' => $new_trade_order_id, 'total_money' => $total_money]);

                $return['status']           = 2;
                $return['trade_order_id']   = $new_trade_order_id;
                $return['order_id']         = $notPay['id'];
                return $return;
            }

        } else {
            // 没有记录，新建订单
            $return['status'] = 1;
            return $return;
        }
    }


    // 生成订单
    public function CreateOrder($user_id, $type, $goods_id, $goods_num, $total_money, $trade_order_id = 0)
    {
        $return = array('status' => 0);
        $new_trade_order_id = $trade_order_id ?: $this->_rand_trade_order_id();
        $data = array(
            'user_id'           => $user_id,
            'type'              => $type,
            'goods_id'          => $goods_id,
            'goods_num'         => $goods_num,
            'total_money'       => $total_money,
            'status'            => self::ORDER_STATUS_NOT_PAY,
            'created_at'        => time(),
            'trade_order_id'    => $new_trade_order_id,
        );

        if (pre_data($data, ['total_money'])) {

            $re = $this->add($data);
            if ($re) {
                $return['status']               = 1;
                $return['trade_order_id']      = $new_trade_order_id;
                $return['order_id']             = $re;
                $return['msg']                  = "添加订单成功";
                return $return;
            } else {
                $return['status']   = -1;
                $return['msg']      = "添加订单失败";
                return $return;
            }
        } else {
            $return['status']   = -2;
            $return['msg']      = "数据不完整";
            return $return;
        }
    }


    // 处理支付回调
    public static function PayCallBack ($attach)
    {
        if (isset($attach['trade_order_id']) && !empty($attach['trade_order_id'])) {
            $order_model    = new self();
            $trade_order_id = $attach['trade_order_id'];
            $order_infos    = $order_model->where(['trade_order_id' => $trade_order_id, 'status' => self::ORDER_STATUS_NOT_PAY])->select();

            if ($order_infos) {
                $total_money = 0;
                foreach ($order_infos as $order) {
                    $total_money += $order['total_money'];
                }
                // 回调支付成功
                if ($attach['total_fee'] >= $total_money) { // 完全付款
                    $data = array(
                        'payment_type'     => $attach['pay_type'],
                        'payment_time'     => time(),
                        'payment_order_id' => $attach['transaction_id'],
                        'payment_money'    => $attach['total_fee'],
                        'status'           => self::ORDER_STATUS_HAS_PAY,
                    );
                } else {// 支付部分
                    $data = array(
                        'payment_type'     => $attach['pay_type'],
                        'payment_time'     => time(),
                        'payment_order_id' => $attach['transaction_id'],
                        'payment_money'    => $attach['total_fee'],
                        'status'           => self::ORDER_STATUS_PAY_FAIL,
                    );
                }
                $order_model->where(['trade_order_id' => $trade_order_id])->save($data);
            } else {
                writeFile('pay call back order info error!!!!!!!!!');
                writeFile($attach);
            }
        } else {
            writeFile('pay call back error!!!!!!!!!');
            writeFile($attach);
        }
    }

    // 取消订单
    // params 订单id，商品id，商品数量
    public function order_refund($order_id, $goods_id, $goods_num)
    {
        // 1 - 设置订单状态
        $this->where(['id' => $order_id])->save(['status' => self::ORDER_STATUS_REFUND, 'refund_status' => self::ORDER_REFUND_STATUS_SELF]);
        // 2 - 增加剩余票数
        M('act_ticket')->where(['act_id' => $goods_id])->save(['remain_num' => ['exp', "remain_num + " . $goods_num]]);
    }
    
    //用原有订单
    public function pay_exisit_order($order_id)
    {
        $new_trade_order_id = 0;
        $order_info = $this->where(['id' => $order_id])->find();
        if ($order_info) {
            $new_trade_order_id = $this->_rand_trade_order_id();
            $this->where(['id' => $order_id])->save(['trade_order_id' => $new_trade_order_id]);
        }
        return $new_trade_order_id;
    }

    private function _rand_trade_order_id()
    {
        return date('YmdHis') . rand(10000, 99999);
    }

}